package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    /**
     * 创建订单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        //1.查询地址信息 => addressBookId
        AddressBook addressBook = addressBookMapper.findByIdAndUserId(ordersSubmitDTO.getAddressBookId(),userId);
        //用户没有填写地址
        if(addressBook == null){
            //出错
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //2.查询当前用户有没有在购物车加入数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findByUserId(userId);
        //购物车没数据
        if(shoppingCartList ==null || shoppingCartList.size() == 0){
            //出错
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3.存订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //绑定数据
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);

        User user = userMapper.findById(userId);
        orders.setUserName(user.getName());

        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        orderMapper.save(orders);

        //4.存订单详情
        //注意事项 => 订单详情的数据来自于购物车数据
        List<OrderDetail> orderDetailList = shoppingCartList.stream()
                .map(shoppingCart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(shoppingCart,orderDetail);
                    orderDetail.setId(null); //这里一定要注意id的问题!!!
                    //设置订单id
                    orderDetail.setOrderId(orders.getId());
                    return orderDetail;
                })
                .collect(Collectors.toList());
        orderDetailMapper.saveDetailList(orderDetailList);

        //5.删除购物车
        shoppingCartMapper.clean(userId);

        //6.组装数据返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
    }

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public void update(String orderNum) {
        //1.根据订单号查询订单
        Orders orders = orderMapper.findOrderByOrderNum(orderNum);
        if(orders == null){
            //抛出异常 订单出问题
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.修改状态
        orders.setStatus(Orders.TO_BE_CONFIRMED); //待接单
        orders.setCheckoutTime(LocalDateTime.now()); //结账时间
        orders.setPayStatus(Orders.PAID);
        orderMapper.update(orders);

        //3.发送给前端(商家管理端 => 提示 有人下单并且支付了,需要商家接单)
        //type
        //orderId
        //content
        HashMap<String,Object> param = new HashMap<>();
        param.put("type",1);
        param.put("orderId",String.valueOf(orders.getId()));
        param.put("content",orders.getNumber());
        try {
            webSocketServer.sendToAllClient(new ObjectMapper().writeValueAsString(param));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.findById(userId);

        //调用微信支付接口，生成预支付交易单
        //这里用的是阿里巴巴的fastjson
        JSONObject jsonObject = null;
        try {
            jsonObject = weChatPayUtil.pay(
                    ordersPaymentDTO.getOrderNumber(), //商户订单号
                    new BigDecimal(0.01), //支付金额，单位 元
                    "描述", //商品描述
                    user.getOpenid() //微信用户的openid
            );
        } catch (Exception e) {
            throw new RuntimeException("支付失败");
        }

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }
}
